package com.amlyc.Lock;

//信号灯法
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Thread(new Player(tv)).start();
        new Thread(new Watcher(tv)).start();

    }

}
class Player implements Runnable{
    TV tv;

    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                this.tv.act("act");

            }else {
                this.tv.act("act2");
            }
        }
    }
}
class Watcher implements Runnable{
    TV tv;

    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {

            this.tv.watch();


        }
    }
}

class TV {
    String voice;
    boolean flag = true;

    public synchronized void act(String voice) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("act ");

        this.voice = voice;
        this.flag = !this.flag;

        this.notifyAll();
    }

    public synchronized void watch(){
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


        this.flag = !this.flag;
        System.out.println("watch ");
        this.notifyAll();
    }



}

